#include "deamon.h"

/*Write pid file*/
static bool write_pidfile(char *fname);

bool set_deamon(){
	pid_t pid;

	if ((pid = fork()) < 0) {
		return false;
	}

	if(pid){
		exit(0);
	}

	setsid();

	if((pid = fork()) < 0){
		return false;
	}

	if(pid){
		exit(0);
	}

	if(write_pidfile(conf_ptr->pidfile)){
		printf("Ftpd deamon start...\t\t[OK]\n");
		set_log_to_file("Ftpd deamon start...\t\t[OK]\n");
		return true;
	}

	return false;
}

char *ftpd_pid_file(char *pidfile){
	FILE *cfp=fopen("/etc/ftpd.d/ftpd.conf", "r");
	char fname[FNAME_LEN]={0};
	char *key, *value;

	if(cfp == NULL){
		puts("config file [/etc/ftpd.d/ftpd.conf] not exists.");
		return pidfile;
	}
	while(fgets(fname, FNAME_LEN, cfp) != NULL){
		fname[strlen(fname)-1] = 0;
		if(fname[0] == '#' || !isalpha(fname[0])){
			bzero(&fname, FNAME_LEN);
			continue;
		}
		//截取第一个项
		key=strtok(fname, CONF_ITEM_DELIM);
		if(key == NULL){
			bzero(&fname, FNAME_LEN);
			continue;
		}
		if((value=strtok(NULL, "=")) == NULL){
			bzero(&fname, FNAME_LEN);
			continue;
		}
		if(!strcmp(PID_FILE, key)){
			strcpy(pidfile, value);
			break;
		}
	}
	fclose(cfp);

	return pidfile;
}

bool cancel_deamon(pid_t pid){
	if(kill(pid,SIGKILL) == -1){
		return false;
	}

	return true;
}

static bool write_pidfile(char *fname) {
	int fd;
	char buff[20];

	if ((fd=open(fname, O_CREAT | O_WRONLY, 0600)) >= 0) {
		bzero(&buff, sizeof(buff));
		sprintf(buff, "%5d\n", (int)getpid());
		if (write(fd, buff, strlen(buff)) == -1) {
			puts("Error writing to pid file send.pid");
		}
		close(fd);

		return true;
	}

	return false;
}
